import { defineStore } from 'pinia';
import { ref } from 'vue';

export interface Exercise {
  id: string;
  name: string;
  description?: string;
  category: string;
  equipment: string;
  muscleGroups: string[];
  instructions: string[];
  images?: string[];
  videos?: string[];
  difficulty: 'beginner' | 'intermediate' | 'advanced';
  createdAt: string;
  updatedAt: string;
}

export interface Category {
  id: string;
  name: string;
  description?: string;
}

export interface Equipment {
  id: string;
  name: string;
  description?: string;
}

export interface ExerciseFilter {
  category?: string;
  equipment?: string;
  muscleGroup?: string;
  difficulty?: 'beginner' | 'intermediate' | 'advanced' | 'all';
  sortBy?: 'name' | 'category' | 'createdAt';
  sortOrder?: 'asc' | 'desc';
}

export const useExerciseStore = defineStore('exercise', () => {
  const exerciseList = ref<Exercise[]>([]);
  const categories = ref<Category[]>([]);
  const equipments = ref<Equipment[]>([]);
  const searchKeyword = ref<string>('');
  const filterOptions = ref<ExerciseFilter>({
    difficulty: 'all',
    sortBy: 'name',
    sortOrder: 'asc',
  });
  const loading = ref<boolean>(false);
  const pagination = ref({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  const setExerciseList = (exercises: Exercise[]) => {
    exerciseList.value = exercises;
  };

  const addExercise = (exercise: Exercise) => {
    exerciseList.value.unshift(exercise);
  };

  const updateExercise = (updatedExercise: Exercise) => {
    const index = exerciseList.value.findIndex(e => e.id === updatedExercise.id);
    if (index !== -1) {
      exerciseList.value[index] = updatedExercise;
    }
  };

  const deleteExercise = (exerciseId: string) => {
    const index = exerciseList.value.findIndex(e => e.id === exerciseId);
    if (index !== -1) {
      exerciseList.value.splice(index, 1);
    }
  };

  const setCategories = (categoryList: Category[]) => {
    categories.value = categoryList;
  };

  const setEquipments = (equipmentList: Equipment[]) => {
    equipments.value = equipmentList;
  };

  const setSearchKeyword = (keyword: string) => {
    searchKeyword.value = keyword;
  };

  const setFilterOptions = (options: Partial<ExerciseFilter>) => {
    filterOptions.value = { ...filterOptions.value, ...options };
  };

  const setLoading = (isLoading: boolean) => {
    loading.value = isLoading;
  };

  const setPagination = (page: number, pageSize: number, total: number) => {
    pagination.value = { current: page, pageSize, total };
  };

  return {
    exerciseList,
    categories,
    equipments,
    searchKeyword,
    filterOptions,
    loading,
    pagination,
    setExerciseList,
    addExercise,
    updateExercise,
    deleteExercise,
    setCategories,
    setEquipments,
    setSearchKeyword,
    setFilterOptions,
    setLoading,
    setPagination,
  };
});